Looping and Conditionals

Looping

In Python the for keyword can be used to iterate over lists.


In [1]:
greek = ["Alpha", "Beta", "Gamma", "Delta"]

In [2]:
for element in greek:
    print(element)


Alpha
Beta
Gamma
Delta

Sometimes you need the index of an element and the element itself while you iterate through a list. This can be achived with the enumerate function.


In [3]:
for i, e in enumerate(greek):
    print(e + " is at index: " + str(i))


Alpha is at index: 0
Beta is at index: 1
Gamma is at index: 2
Delta is at index: 3

The above is taking advantage of tuple decomposition, because enumerate generates a list of tuples. Let's look at this more explicitly.


In [4]:
list_of_tuples = [(1,2,3),(4,5,6), (7,8,9)]
for (a, b, c) in list_of_tuples:
    print(a + b + c)


6
15
24

If you have two or more lists you want to iterate over together you can use the zip function.


In [5]:
for e1, e2 in zip(greek, greek):
    print("Double Greek: " + e1 + e2)


Double Greek: AlphaAlpha
Double Greek: BetaBeta
Double Greek: GammaGamma
Double Greek: DeltaDelta

You can also iterate over tuples


In [6]:
for i in (1,2,3):
    print(i)


1
2
3

and dictionaries in various ways


In [7]:
elements = {
    "H": "Hydrogen",
    "He": "Helium",
    "Li": "Lithium",
}

In [8]:
for key in elements: # Over the keys
    print(key)


H
Li
He

In [9]:
for key, val in elements.items(): # Over the keys and values 
    print(key + ": " + val)


H: Hydrogen
Li: Lithium
He: Helium

In [10]:
for val in elements.values():
    print(val)


Hydrogen
Lithium
Helium

Conditionals

Conditionals are a way of having certain actions occur only on specific conditions.


In [11]:
x = 5

if x % 2 == 0: # Checks if x is even
    print(str(x) + " is even!!!")
    
if x % 2 == 1: # Checks if x is odd
    print(str(x) + " is odd!!!")


5 is odd!!!

In the above example the second condition is somewhat redundant because if x is not even it is odd. There's a better way of expressing this.


In [12]:
if x % 2 == 0: # Checks if x is even
    print(str(x) + " is even!!!")
else: # x is odd
    print(str(x) + " is odd!!!")


5 is odd!!!

You can have more than two conditions.


In [13]:
if x % 4 == 0:
    print("x divisible by 4")
elif x % 3 == 0 and x % 5:
    print("x divisible by 3 and 5")
elif x % 1 == 0:
    print("x divisible by 1")
else:
    print("I give up")


x divisible by 1

Note how only the first conditional branch that matches gets executed. The else conditions is a catch all condition that would have executed if none of the other branches had been chosen.

Bonus: Loop Comprehensions

You can use the for keyword to generate new lists with data using list comprehensions.


In [14]:
r1 = []
for i in range(10):
    r1.append(i**2)

# Equivalent to the loop above.
r2 = [i**2 for i in range(10)]

print(r1)
print(r2)


[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

In [15]:
r1 = []
for i in range(30):
    if (i%2 == 0 and i%3 == 0):
        r1.append(i)

# Equivalent to the loop above.
r2 = [i for i in range(30) if i%2==0 and i%3==0]

print(r1)
print(r2)


[0, 6, 12, 18, 24]
[0, 6, 12, 18, 24]